package com.net.library.net;

import android.os.AsyncTask;
import com.socks.library.KLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * Created by 吴昶 on 2018/1/23.
 */

public class FileDownLoad {

    private static String savePath= "文件保存路径";
    private static String fileName;
    private static File file;

    public interface DownLoadListener{
        void DownSuccessListener(String filePath);
        void DownDefeatedListener(String failMsg);
        void DownCancelListener(String failMsg);
        void DownLoadProgress(Integer duration, Integer progress);
    }
    /**
     * AsyncTask  下载
     */
    static class DownloadAsyncTas extends AsyncTask<String, Void, String> {
        private DownLoadListener listener;
        public DownloadAsyncTas(DownLoadListener listener) {
            this.listener=listener;
        }

        @Override
        protected String doInBackground(String... params) {
            //execute方法中传过来的下载的地址
            String s = params[0];
            String fileName = params[1];
//            fileName=FileUtil.getFileNameForUrl(s);
            file=new File(savePath,fileName);
            try {
                if(!file.exists()){
                    file.createNewFile();
                }else {
                    return file.getPath();
                }
                URL url = new URL(s);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("Accept-Encoding", "identity");
                byte[] bytes = new byte[1024];
                int len = -1;
                int downlen=1;
                InputStream in = conn.getInputStream();
                int all=conn.getContentLength();
                FileOutputStream out = new FileOutputStream(file);
                while( (len = in.read(bytes)) != -1 ){
                    out.write(bytes, 0, len);
                    downlen+=len;
                    out.flush();
                    if (listener!=null){
                        listener.DownLoadProgress(all,downlen);
                    }
                }
                out.close();
                in.close();
                return file.getPath().toString();
            } catch (MalformedURLException e) {
                e.printStackTrace();
                //调用监听接口告知下载失败，退出弹框
                file.delete();
                if(this.listener!=null) {
                    this.listener.DownDefeatedListener(e.getMessage());
                }
            } catch (IOException e) {
                e.printStackTrace();
                file.delete();
                //调用监听接口告知下载失败，退出弹框
                if(this.listener!=null) {
                    this.listener.DownDefeatedListener(e.getMessage());
                }
            }
            return null;
        }


        @Override
        protected void onPostExecute(String integer) {
            super.onPostExecute(integer);
            if(integer==null||integer.equals("")){
                if(this.listener!=null) {
                    this.listener.DownDefeatedListener("文件不存在");
                }
            }else if(this.listener!=null) {
                this.listener.DownSuccessListener(integer);
            }
        }
    }

    /**
     * 根据url直接获取文件
     * @param url
     */
    public static void getFileForUrl(String url, String fileName, DownLoadListener listener){
        if(url==null || url.equals("") || url.equals("null")){
            listener.DownDefeatedListener("");
            return;
        }
        DownloadAsyncTas task=new DownloadAsyncTas(listener);
        KLog.d(url);
        task.execute(url,fileName);
    }

    /**
     * 根据url列表获取文件
     * @param urls
     * @param listener
     */
    public static void getFileForUrls(List<String> urls, DownLoadListener listener){
        if(urls==null||urls.size()==0){
            if(listener!=null) {
                listener.DownDefeatedListener("");
            }
            return;
        }
        for(String url:urls) {
            if (url == null || url.equals("") || url.equals("null")) {
                if(listener!=null) {
                    listener.DownDefeatedListener("");
                }
                continue;
            }
            DownloadAsyncTas task = new DownloadAsyncTas(listener);
            task.execute(url);
        }
        if(listener!=null){
            listener.DownCancelListener("");
        }
    }

}
